<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    switchFullscreen
    @cancel="handleCancel"
    :footer="null"
    cancelText="关闭">

    <a-row :gutter="10">
      <a-col :span="8">
        <a-card title="已选应用" :bodyStyle="bodyStyle">
          <a-input-search v-model="appValue" @search="onSearch" style="width:100%;margin-top: 10px" placeholder=""/>
          <a-tree
            :selectedKeys="selectedKeys"
            :treeData="appTree"
          />
        </a-card>
      </a-col>

      <a-col :span="8">
        <a-card title="已选应用默认角色" :bodyStyle="bodyStyle">
          <a-tree
            :selectedKeys="selectedKeysRole"
            :treeData="treeRole"
            @select="onSelectRole"
          />
        </a-card>
      </a-col>
      <a-col :span="8">
        <a-card title="菜单/按钮权限" :bodyStyle="bodyStyle">
          <a-tree
            :checkable="true"
            :selectedKeys="selectedKeysPermission"
            :checkedKeys="checkedKeysPermission"
            :treeData="permissionTree"
            @expand="expandPermission"
            :checkStrictly="false"
            :expandedKeys="expandedKeys"
          />
        </a-card>
      </a-col>
    </a-row>

    <div style="min-height: 20px;">
      <a-dropdown style="float: left" :trigger="['click']" placement="topCenter">
        <a-menu slot="overlay">
          <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
          <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
        </a-menu>
        <a-button>
          权限树操作 <a-icon type="up" />
        </a-button>
      </a-dropdown>
    </div>

  </j-modal>
</template>

<script>
  import { getAppTree, listTenantAppTree, getPermissionTree, getTenantDetailPermission } from './service'

  export default {
    name: 'TenantAppDetailModal',
    components: {
    },
    data () {
      return {
        title: '应用详情',
        width: 1500,
        visible: false,

        tenantId: '',

        appValue: '',

        selectedKeys: [],
        appTree: [],

        selectedKeysRole: [],
        checkedKeysRole: [],
        existTreeRole: [],
        treeRole: [],

        selectedKeysPermission: [],
        checkedKeysPermission: [],
        permissionTree: [],
        permissionIds: [],
        expandedKeys: [],

        savePermissions: {},
        currentAppId: '',

        bodyStyle: { 'min-height': '500px' },

        url: {
        }
      }
     },
    methods: {
      close () {
        this.$emit('close');
        this.visible = false;
      },
      edit (record) {
        this.tenantId = record.id;
        this.appValue = ''

        this.visible = true

        this.loadTree('', this.tenantId);

        this.selectedKeysRole = [];
        this.loadTreeRole(record.id);

        this.checkedKeysPermission = [];
        this.permissionTree = [];
        this.getTenantPermission(record.id)
      },
      handleCancel () {
        this.close()
      },
      loadTree(appName, tenantId) {
        let that = this
        appName = appName || '';
        getAppTree({ name: appName, tenant_id: tenantId }).then((res) => {
          if (res.success) {
            that.appTree = res.result;
          } else {
            this.$message.error(res.message)
          }
        })
      },
      onSearch(value) {
        this.loadTree(value, this.tenantId)
      },

      loadTreeRole(tenantId) {
        let that = this
        listTenantAppTree(tenantId).then((res) => {
          if (res.success) {
            that.treeRole = res.result;
            that.existTreeRole = {};
            res.result.forEach(function (item) {
              that.existTreeRole[item.appId] = item
            })
          } else {
            that.$message.error(res.message)
          }
        })
      },
      onSelectRole(selectedKeys) {
        if (selectedKeys.length > 0) {
          let roleId = selectedKeys[0];
          let appId;
          let queryRoleId;
          this.treeRole.forEach(function (item) {
            if (roleId === item.key) {
              appId = item['appId'];
              queryRoleId = roleId;
            }
          })
          this.currentAppId = appId;
          this.getPermissionTree(queryRoleId, appId)
        } else {
          this.currentAppId = '';
          this.permissionTree = [];
          this.permissionIds = [];
          this.checkedKeysPermission = [];
        }
        this.selectedKeysRole = selectedKeys
      },
      getTenantPermission(tenantId) {
        let that = this;
        getTenantDetailPermission(tenantId).then((res) => {
          if (res.success) {
            that.savePermissions = {};
            res.result.forEach(function (item) {
              if (that.savePermissions[item.appId] === undefined) {
                that.savePermissions[item.appId] = { permissionIds: [], leafPermission: [] };
              }
              that.savePermissions[item.appId]['permissionIds'].push(item.permissionId);
              if (item.isLeaf === 1) {
                that.savePermissions[item.appId]['leafPermission'].push(item.permissionId);
              }
            });
          } else {
            this.$message.error(res.message)
          }
        })
      },
      getPermissionTree(roleId, appId) {
        let that = this
        getPermissionTree(roleId).then((res) => {
          if (res.success) {
            this.permissionTree = res.result.permissions;
            this.permissionIds = res.result.permissionIds;
            if (that.savePermissions[appId] !== undefined) {
              that.checkedKeysPermission = that.savePermissions[appId]['leafPermission'];
              that.savePermissions[appId]['parentRoleId'] = roleId;
            } else {
              that.savePermissions[appId] = { permissionIds: [], 'parentRoleId': roleId };
            }
          } else {
            this.$message.error(res.message)
          }
        })
      },
      expandAll() {
        this.expandedKeys = this.permissionIds
      },
      closeAll() {
        this.expandedKeys = []
      },
      expandPermission(expandedKeys) {
        this.expandedKeys = expandedKeys
      }
    }
  }
</script>
